<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">计量单位管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="units" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="计量单位"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增单位
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="单位名称">
          <el-input v-model="searchForm.name" placeholder="请输入单位名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="长度" value="length" />
            <el-option label="重量" value="weight" />
            <el-option label="体积" value="volume" />
            <el-option label="面积" value="area" />
            <el-option label="数量" value="quantity" />
            <el-option label="时间" value="time" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchEnable">批量启用</el-button>
              <el-button size="small" type="warning" @click="handleBatchDisable">批量停用</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="code" label="单位代码" width="120" />
        <el-table-column prop="name" label="单位名称" width="150" />
        <el-table-column prop="symbol" label="符号" width="100" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="baseUnit" label="基本单位" width="120" />
        <el-table-column prop="conversionRate" label="换算比率" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button 
              link 
              :type="row.status === 1 ? 'warning' : 'success'" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="单位代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入单位代码" />
        </el-form-item>
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="符号" prop="symbol">
          <el-input v-model="form.symbol" placeholder="请输入符号，如：kg、m" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="长度" value="length" />
            <el-option label="重量" value="weight" />
            <el-option label="体积" value="volume" />
            <el-option label="面积" value="area" />
            <el-option label="数量" value="quantity" />
            <el-option label="时间" value="time" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="基本单位" prop="baseUnit">
          <el-input v-model="form.baseUnit" placeholder="基本单位（用于换算）" />
        </el-form-item>
        <el-form-item label="换算比率" prop="conversionRate">
          <el-input-number v-model="form.conversionRate" :min="0" :precision="4" />
          <span class="form-tip">相对于基本单位的比率</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: ''
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'code', label: '单位代码' },
  { prop: 'name', label: '单位名称' },
  { prop: 'symbol', label: '符号' },
  { prop: 'type', label: '类型' },
  { prop: 'baseUnit', label: '基本单位' },
  { prop: 'conversionRate', label: '换算比率' },
  { prop: 'status', label: '状态' },
  { prop: 'remark', label: '备注' }
]

// 表格数据
const tableData = ref([
  { id: 1, code: 'PCS', name: '件', symbol: '件', type: 'quantity', baseUnit: '件', conversionRate: 1, status: 1, remark: '基本计数单位' },
  { id: 2, code: 'KG', name: '千克', symbol: 'kg', type: 'weight', baseUnit: '克', conversionRate: 1000, status: 1, remark: '重量单位' },
  { id: 3, code: 'G', name: '克', symbol: 'g', type: 'weight', baseUnit: '克', conversionRate: 1, status: 1, remark: '重量基本单位' },
  { id: 4, code: 'M', name: '米', symbol: 'm', type: 'length', baseUnit: '米', conversionRate: 1, status: 1, remark: '长度单位' },
  { id: 5, code: 'CM', name: '厘米', symbol: 'cm', type: 'length', baseUnit: '米', conversionRate: 0.01, status: 1, remark: '长度单位' },
  { id: 6, code: 'L', name: '升', symbol: 'L', type: 'volume', baseUnit: '升', conversionRate: 1, status: 1, remark: '体积单位' },
  { id: 7, code: 'ML', name: '毫升', symbol: 'ml', type: 'volume', baseUnit: '升', conversionRate: 0.001, status: 1, remark: '体积单位' },
  { id: 8, code: 'BOX', name: '箱', symbol: '箱', type: 'quantity', baseUnit: '件', conversionRate: 12, status: 1, remark: '包装单位' }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 8
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增单位')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  symbol: '',
  type: '',
  baseUnit: '',
  conversionRate: 1,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入单位代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

// 获取类型标签
const getTypeTag = (type) => {
  const tagMap = {
    length: 'primary',
    weight: 'success',
    volume: 'info',
    area: 'warning',
    quantity: '',
    time: 'danger',
    other: 'info'
  }
  return tagMap[type] || ''
}

// 获取类型名称
const getTypeLabel = (type) => {
  const labelMap = {
    length: '长度',
    weight: '重量',
    volume: '体积',
    area: '面积',
    quantity: '数量',
    time: '时间',
    other: '其他'
  }
  return labelMap[type] || type
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.type = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量启用
const handleBatchEnable = () => {
  ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个单位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 1
    })
    ElMessage.success('批量启用成功')
    selectedRows.value = []
  })
}

// 批量停用
const handleBatchDisable = () => {
  ElMessageBox.confirm(`确定要停用选中的 ${selectedRows.value.length} 个单位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 0
    })
    ElMessage.success('批量停用成功')
    selectedRows.value = []
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个单位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    console.log('批量删除:', ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    handleSearch()
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  console.log('导入成功:', result)
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增单位'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    symbol: '',
    type: '',
    baseUnit: '',
    conversionRate: 1,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑单位'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除单位 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log('删除:', row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = (row) => {
  const status = row.status === 1 ? 0 : 1
  const text = status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确定要${text}单位 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = status
    ElMessage.success(`${text}成功`)
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style>

